<?php
/**
 * 管理后台功能类
 *
 * @package DeepSeekAISummarizer
 * @since 3.7.2
 */

// 防止直接访问
if (!defined('ABSPATH')) {
    exit;
}

// 防止重复声明类
if (!class_exists('DeepSeekAI_Admin')) {

class DeepSeekAI_Admin {
    
    private $plugin;
    
    // 构造与初始化
    /**
     * 构造函数，注册所有后台钩子
     */
    public function __construct($plugin) {
        $this->plugin = $plugin;
        
        // 一次性迁移旧设置到新结构 (V2, 确保所有字段都被迁移)
        if (!get_option('deepseek_ai_settings_migrated_to_unified_configs_v2')) {
            $this->migrate_to_unified_configs();
            update_option('deepseek_ai_settings_migrated_to_unified_configs_v2', true);
        }
        
        // 注册设置
        add_action('admin_init', array($this, 'register_settings'));
        
        // 添加管理菜单
        add_action('admin_menu', array($this, 'add_admin_menu'));
        
        // 加载样式和脚本
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
        
        add_action('wp_ajax_deepseek_ai_save_global_password', array($this, 'ajax_save_global_password'));
        add_action('wp_ajax_deepseek_ai_generate_guide_html', array($this, 'ajax_generate_guide_html'));
        add_action('wp_ajax_deepseek_ai_toggle_global_password', array($this, 'ajax_toggle_global_password'));
        add_action('wp_ajax_deepseek_ai_manual_update_check', array($this, 'ajax_manual_update_check'));
        add_action('wp_ajax_deepseek_ai_do_plugin_update', array($this, 'ajax_do_plugin_update'));
    }
    
    /**
     * 将旧的、分散的设置项迁移到新的统一配置结构中
     * 这个操作只会执行一次
     */
    public function migrate_to_unified_configs() {
        $this->plugin->info_log('开始迁移插件设置为统一配置结构...');
        $new_configs = get_option('deepseek_ai_provider_configs', array());

        $migration_map = [
            'zhipu' => [
                'api_key' => 'zhipu_ai_api_key',
                'model' => 'zhipu_ai_model',
                'max_tokens' => 'zhipu_ai_max_tokens',
                'temperature' => 'zhipu_ai_temperature',
            ],
            'deepseek' => [
                'api_key' => 'deepseek_ai_api_key',
                'model' => 'deepseek_ai_model',
                'max_tokens' => 'deepseek_ai_max_tokens',
                'temperature' => 'deepseek_ai_temperature',
            ],
            'volcengine' => [
                'api_key' => 'volcengine_ai_api_key',
                'model' => 'volcengine_ai_model',
                'max_tokens' => 'volcengine_ai_max_tokens',
                'temperature' => 'volcengine_ai_temperature',
            ],
        ];

        $migrated_something = false;
        foreach ($migration_map as $provider_id => $field_map) {
            $provider_config = array();
            foreach ($field_map as $new_key => $old_option_name) {
                $old_value = get_option($old_option_name);
                
                // 只有当旧选项确实存在且有值时才迁移
                if ($old_value !== false) {
                    $provider_config[$new_key] = $old_value;
                    // 删除旧选项以保持数据库清洁
                    delete_option($old_option_name);
                    $migrated_something = true;
                }
            }

            if (!empty($provider_config)) {
                // 合并到新的配置结构中
                if (!isset($new_configs[$provider_id])) {
                    $new_configs[$provider_id] = array();
                }
                $new_configs[$provider_id] = array_merge($new_configs[$provider_id], $provider_config);
                $this->plugin->info_log("为 '{$provider_id}' 迁移了 " . count($provider_config) . " 个设置项。");
            }
        }

        if ($migrated_something) {
            update_option('deepseek_ai_provider_configs', $new_configs);
            $this->plugin->info_log('设置迁移完成，新的统一配置已保存。');
        } else {
            $this->plugin->info_log('无需迁移，未找到旧的设置项。');
        }
    }
    
    // 设置注册
    /**
     * 注册所有设置项
     */
    public function register_settings() {
        // 注册设置组
        register_setting('deepseek_ai_settings', 'deepseek_ai_provider', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => 'zhipu'
        ));

        // 统一存储所有提供商的配置
        register_setting('deepseek_ai_settings', 'deepseek_ai_provider_configs', array(
            'type' => 'array',
            'sanitize_callback' => array($this, 'sanitize_provider_configs'),
            'default' => array()
        ));
        
        register_setting('deepseek_ai_settings', 'deepseek_ai_force_display', array(
            'type' => 'boolean',
            'sanitize_callback' => 'rest_sanitize_boolean',
            'default' => false
        ));
        
        // 注册调试设置
        register_setting('deepseek_ai_settings', 'deepseek_ai_debug_enabled', array(
            'type' => 'boolean',
            'sanitize_callback' => 'rest_sanitize_boolean',
            'default' => false
        ));
        
        register_setting('deepseek_ai_settings', 'deepseek_ai_debug_level', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => 'info'
        ));
        
        register_setting('deepseek_ai_settings', 'deepseek_ai_debug_frontend', array(
            'type' => 'boolean',
            'sanitize_callback' => 'rest_sanitize_boolean',
            'default' => false
        ));
        
        register_setting('deepseek_ai_settings', 'deepseek_ai_debug_ajax', array(
            'type' => 'boolean',
            'sanitize_callback' => 'rest_sanitize_boolean',
            'default' => false
        ));
        
        register_setting('deepseek_ai_settings', 'deepseek_ai_debug_api', array(
            'type' => 'boolean',
            'sanitize_callback' => 'rest_sanitize_boolean',
            'default' => false
        ));
        
        register_setting('deepseek_ai_settings', 'deepseek_ai_global_password_hash');
        register_setting('deepseek_ai_settings', 'deepseek_ai_password_hint');
        register_setting('deepseek_ai_settings', 'deepseek_ai_password_guide_html');
        register_setting('deepseek_ai_settings', 'deepseek_ai_guide_prompt', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => '请生成一段适合放在密码输入框下方的HTML引导内容，要求如下：只返回HTML标签片段，不要出现任何代码块标记（如```、```html、```代码等）；不要使用<style>标签；所有样式请用内联style属性写在标签上；内容可包含关注公众号、二维码、联系方式等，字数80字内；只返回HTML标签本身，不要有多余的换行、缩进或解释说明，不要有其它任何内容。'
        ));
        
        register_setting('deepseek_ai_settings', 'deepseek_ai_global_password_enabled', array(
            'type' => 'boolean',
            'sanitize_callback' => 'rest_sanitize_boolean',
            'default' => true
        ));
    }
    
    /**
     * 清理和验证提供商配置数组
     *
     * @param array $input 待处理的输入数组
     * @return array 处理后的数组
     */
    public function sanitize_provider_configs($input) {
        // 从数据库中获取已保存的完整配置，作为基础
        $sanitized_configs = get_option('deepseek_ai_provider_configs', array());

        // 如果传入的输入不是数组，则直接返回原始配置，防止意外清空
        if (!is_array($input)) {
            return $sanitized_configs;
        }
    
        $models_config = DeepSeekAI_Models_Config::get_instance();
        $providers = $models_config->get_providers();
        $provider_ids = array_map(function($p) { return $p['id']; }, $providers);

        // 遍历本次表单提交的数据
        foreach ($input as $provider_id => $configs) {
            $provider_key = sanitize_key($provider_id);

            // 只处理在JSON中定义的、合法的服务商
            if (!in_array($provider_key, $provider_ids)) {
                continue;
            }
            
            // 将提交的数据（在清理后）合并到现有的配置数组中
            if (is_array($configs)) {
                if (isset($configs['api_key'])) {
                    $sanitized_configs[$provider_key]['api_key'] = sanitize_text_field($configs['api_key']);
                }
                if (isset($configs['model'])) {
                    $sanitized_configs[$provider_key]['model'] = sanitize_text_field($configs['model']);
                }
                if (isset($configs['max_tokens'])) {
                    $sanitized_configs[$provider_key]['max_tokens'] = absint($configs['max_tokens']);
                }
                if (isset($configs['temperature'])) {
                    $sanitized_configs[$provider_key]['temperature'] = floatval($configs['temperature']);
                }
            }
        }
    
        // 返回合并后的、完整的配置数组
        return $sanitized_configs;
    }
    
    // 菜单与脚本加载
    public function add_admin_menu() {
        add_menu_page(
            '爱奇吉摘要 设置',
            '爱奇吉摘要',
            'manage_options',
            'deepseek-ai-settings',
            array($this, 'admin_page'),
            plugins_url('img/cblogo.svg', dirname(__FILE__)),
            null
        );
    }
    
    public function enqueue_admin_scripts($hook) {
        // 添加调试日志
        $this->plugin->debug_log('当前页面钩子: ' . $hook);
        
        // 检查是否在文章编辑页面或设置页面
        if ($hook === 'settings_page_deepseek-ai-settings') {
            // 加载样式
            wp_enqueue_style('deepseek-ai-admin', DEEPSEEK_AI_PLUGIN_URL . 'css/style.css', array(), $this->plugin->get_version());
            $this->plugin->debug_log('已加载管理页面样式文件: ' . DEEPSEEK_AI_PLUGIN_URL . 'css/style.css');
            
            // 加载WordPress媒体库（用于图片上传）
            if (in_array($hook, array('post.php', 'post-new.php'))) {
                wp_enqueue_media();
                $this->plugin->debug_log('已加载WordPress媒体库');
            }
            
            // 加载脚本
            wp_enqueue_script('deepseek-ai-admin', DEEPSEEK_AI_PLUGIN_URL . 'js/scripts.js', array('jquery'), $this->plugin->get_version(), true);
            $this->plugin->debug_log('已加载管理页面脚本文件: ' . DEEPSEEK_AI_PLUGIN_URL . 'js/scripts.js');
            
            // 本地化脚本
            wp_localize_script('deepseek-ai-admin', 'deepseek_ai_ajax', array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('deepseek_ai_nonce'),
                'generating_text' => '正在生成中...',
                'error_text' => '生成失败，请检查API设置',
                'plugin_url' => DEEPSEEK_AI_PLUGIN_URL,
                'version' => $this->plugin->get_version(),
                'plugin_name' => 'DeepSeek AI 文章摘要生成器',
                'debug_enabled' => $this->plugin->is_debug_enabled(),
                'debug_level' => $this->plugin->get_debug_level()
            ));
            $this->plugin->debug_log('已本地化脚本数据，版本号: ' . $this->plugin->get_version());
        }
    }
    
    // 设置页面渲染
    public function admin_page() {
        if (!current_user_can('manage_options')) {
            return;
        }
        
        // 检查是否有设置更新
        if (isset($_GET['settings-updated'])) {
            $this->plugin->update_debug_settings();
            add_settings_error('deepseek_ai_messages', 'deepseek_ai_message', '设置已保存', 'updated');
            $this->plugin->info_log('插件设置已更新');
        }
        
        // 获取所有模型配置和已保存的设置
        $models_config = DeepSeekAI_Models_Config::get_instance();
        $all_providers_config = $models_config->get_providers();
        $saved_provider_configs = get_option('deepseek_ai_provider_configs', array());
        ?>
        <style>
            .deepseek-ai-settings-wrap .notice { margin: 0 0 20px 0; }
            .deepseek-ai-settings-layout { display: flex; gap: 20px; }
            .deepseek-ai-settings-sidebar { flex: 0 0 200px; }
            .deepseek-ai-settings-sidebar ul { list-style: none; margin: 0; padding: 0; }
            .deepseek-ai-settings-sidebar li {
                padding: 12px 15px;
                cursor: pointer;
                border-radius: 8px;
                margin-bottom: 5px;
                font-size: 14px;
                font-weight: 500;
                color: #444;
                display: flex;
                align-items: center;
                gap: 10px;
                transition: background-color 0.2s, color 0.2s;
            }
            .deepseek-ai-settings-sidebar li:before {
                font-family: 'dashicons';
                font-size: 20px;
            }
            .deepseek-ai-settings-sidebar li[data-tab="api"]:before { content: "\f521"; }
            .deepseek-ai-settings-sidebar li[data-tab="features"]:before { content: "\f111"; }
            .deepseek-ai-settings-sidebar li[data-tab="debug"]:before { content: "\f308"; }
            .deepseek-ai-settings-sidebar li[data-tab="update"]:before { content: "\f463"; }

            .deepseek-ai-settings-sidebar li:hover { background-color: #f0f0f1; }
            .deepseek-ai-settings-sidebar li.active { background-color: #4D6BFE; color: white; }

            .deepseek-ai-settings-content { flex: 1; background: #fff; padding: 20px 30px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }
            .settings-tab { display: none; }
            .settings-tab.active { display: block; animation: fadeIn 0.3s; }
            @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }

            .settings-tab h2 { font-size: 22px; margin-top: 0; margin-bottom: 25px; padding-bottom: 15px; border-bottom: 1px solid #ddd; }
            .form-table { border: 0; }
            .form-table th, .form-table td { padding: 15px 0; }
            .form-table th { font-weight: 600; font-size: 14px; width: 220px; }
            .form-table td .description { font-size: 13px; color: #666; }
            .form-table input[type="text"], .form-table input[type="password"], .form-table input[type="number"], .form-table select, .form-table textarea {
                width: 100%;
                max-width: 450px;
                padding: 8px 12px;
                border-radius: 6px;
                border: 1px solid #ddd;
            }
            .form-table textarea { max-width: 100%; }
            #debug-log-content { white-space: pre-wrap; font-family: monospace; font-size: 12px; background: #f9f9f9; border: 1px solid #ddd; padding: 10px; max-height: 400px; overflow-y: auto; margin-top: 10px; }
        </style>

        <div class="wrap deepseek-ai-settings-wrap">
            
            <div class="deepseek-ai-settings-header" style="display: flex; align-items: center; margin-bottom: 30px; padding: 20px; background: linear-gradient(135deg, #1a1f3c 0%, #2d3a6d 100%); border-radius: 15px; color: white; box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);">
                <img src="<?php echo plugin_dir_url(dirname(__FILE__)) . 'img/logo.svg'; ?>" alt="爱奇吉智能摘要" style="width: 40px; height: 40px; margin-right: 15px; filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.3));" />
                <div>
                    <div style="margin: 0; color: #ffffff; font-size: 24px; font-weight: 600; text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);"><?php echo esc_html(get_admin_page_title()); ?></div>
                    <p style="margin: 5px 0 0 0; color: rgba(255, 255, 255, 0.8); font-size: 14px;">配置您的 AI 内容生成设置</p>
                </div>
            </div>

            <div class="deepseek-ai-settings-layout">
                <div class="deepseek-ai-settings-sidebar">
                    <ul>
                        <li class="active" data-tab="api">API 设置</li>
                        <li data-tab="features">功能设置</li>
                        <li data-tab="debug">调试设置</li>
                        <li data-tab="update">插件更新</li>
                    </ul>
                </div>

                <div class="deepseek-ai-settings-content">
                    <form action="options.php" method="post">
                        <?php settings_errors('deepseek_ai_messages'); ?>
                        <?php settings_fields('deepseek_ai_settings'); ?>

                        <!-- API 设置 Tab -->
                        <div id="tab-api" class="settings-tab active">
                            <h2>API 设置</h2>
                            <table class="form-table">
                                <tr valign="top">
                                    <th scope="row">AI 服务提供商</th>
                                    <td>
                                        <select name="deepseek_ai_provider" id="ai_provider_select">
                                        <?php
                                            $current_provider = get_option('deepseek_ai_provider', 'zhipu');
                                            foreach ($all_providers_config as $provider) {
                                                $recommended_text = isset($provider['is_recommended']) && $provider['is_recommended'] ? '（推荐）' : '';
                                                echo '<option value="' . esc_attr($provider['id']) . '"' . selected($current_provider, $provider['id'], false) . '>' . esc_html($provider['name']) . $recommended_text . '</option>';
                                            }
                                        ?>
                                        </select>
                                        <p class="description">选择您要使用的AI服务模型。更改此选项后，请务必点击下方的"保存设置"按钮。</p>
                                    </td>
                                </tr>
                            </table>

                            <?php foreach ($all_providers_config as $provider): 
                                $provider_id = $provider['id'];
                                $saved_config = $saved_provider_configs[$provider_id] ?? [];
                            ?>
                            <div class="provider-settings-block" id="provider-settings-<?php echo esc_attr($provider_id); ?>" style="display:none;">
                                <h3 style="margin-top: 30px; padding-top: 20px; border-top: 1px solid #eee;"><?php echo esc_html($provider['name']); ?> 设置</h3>
                                <table class="form-table">
                                    <tr valign="top">
                                        <th scope="row"><label for="api-key-<?php echo esc_attr($provider_id); ?>"><?php echo esc_html($provider['name']); ?> API Key</label></th>
                                        <td>
                                            <input type="password" 
                                                   id="api-key-<?php echo esc_attr($provider_id); ?>"
                                                   name="deepseek_ai_provider_configs[<?php echo esc_attr($provider_id); ?>][api_key]" 
                                                   value="<?php echo esc_attr($saved_config['api_key'] ?? ''); ?>" 
                                                   class="regular-text" />
                                            <p class="description"><?php echo esc_html($provider['description']['api_key'] ?? '请输入您的 API Key。'); ?></p>
                                        </td>
                                    </tr>
                                    <tr valign="top">
                                        <th scope="row"><label for="model-<?php echo esc_attr($provider_id); ?>"><?php echo esc_html($provider['name']); ?> 模型</label></th>
                                        <td>
                                            <select id="model-<?php echo esc_attr($provider_id); ?>" name="deepseek_ai_provider_configs[<?php echo esc_attr($provider_id); ?>][model]">
                                                <?php foreach ($provider['models'] as $model): ?>
                                                    <option value="<?php echo esc_attr($model['id']); ?>" <?php selected($saved_config['model'] ?? ($provider['models'][0]['id'] ?? ''), $model['id']); ?>>
                                                        <?php echo esc_html($model['name'] . (!empty($model['description']) ? ' (' . $model['description'] . ')' : '')); ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                            <p class="description"><?php echo wp_kses_post($provider['description']['model'] ?? '请选择要使用的模型。'); ?></p>
                                        </td>
                                    </tr>
                                    <tr valign="top">
                                        <th scope="row"><label for="max-tokens-<?php echo esc_attr($provider_id); ?>"><?php echo esc_html($provider['name']); ?> 最大Token数</label></th>
                                        <td>
                                            <?php 
                                                $tokens_config = $provider['parameters']['max_tokens'];
                                                $saved_tokens = $saved_config['max_tokens'] ?? $tokens_config['default'];
                                            ?>
                                            <input type="number" 
                                                   id="max-tokens-<?php echo esc_attr($provider_id); ?>"
                                                   name="deepseek_ai_provider_configs[<?php echo esc_attr($provider_id); ?>][max_tokens]" 
                                                   value="<?php echo esc_attr($saved_tokens); ?>"
                                                   min="<?php echo esc_attr($tokens_config['min']); ?>"
                                                   max="<?php echo esc_attr($tokens_config['max']); ?>"
                                                   step="1" />
                                            <p class="description"><?php echo esc_html($provider['description']['max_tokens'] ?? '设置生成内容的最大长度。'); ?></p>
                                        </td>
                                    </tr>
                                    <tr valign="top">
                                        <th scope="row"><label for="temperature-<?php echo esc_attr($provider_id); ?>"><?php echo esc_html($provider['name']); ?> Temperature</label></th>
                                        <td>
                                            <?php 
                                                $temp_config = $provider['parameters']['temperature'];
                                                $saved_temp = $saved_config['temperature'] ?? $temp_config['default'];
                                                $step = $temp_config['step'] ?? '0.1'; // 确保step总是小数
                                            ?>
                                            <input type="number" 
                                                   id="temperature-<?php echo esc_attr($provider_id); ?>"
                                                   name="deepseek_ai_provider_configs[<?php echo esc_attr($provider_id); ?>][temperature]" 
                                                   value="<?php echo esc_attr($saved_temp); ?>"
                                                   min="<?php echo esc_attr($temp_config['min']); ?>"
                                                   max="<?php echo esc_attr($temp_config['max']); ?>"
                                                   step="<?php echo esc_attr($step); ?>" />
                                            <p class="description"><?php echo esc_html($provider['description']['temperature'] ?? '控制生成内容的随机性。'); ?></p>
                                        </td>
                                    </tr>
                                </table>
                            </div>
                            <?php endforeach; ?>
                        </div>

                        <!-- 功能设置 Tab -->
                        <div id="tab-features" class="settings-tab">
                            <h2>功能设置</h2>
                            <table class="form-table">
                                <tr valign="top">
                                    <th scope="row">强制显示摘要</th>
                                    <td>
                                        <label><input type="checkbox" name="deepseek_ai_force_display" value="1" <?php checked(1, get_option('deepseek_ai_force_display', false), true); ?> /> 启用</label>
                                        <p class="description">启用后，摘要将在所有支持的主题中强制显示，即使主题不完全兼容也能正常显示摘要内容。</p>
                                    </td>
                                </tr>
                                <tr valign="top">
                                    <th scope="row">全局访问密码</th>
                                    <td>
                                        <?php $global_pw_enabled = get_option('deepseek_ai_global_password_enabled', true); ?>
                                        <label><input type="checkbox" id="deepseek_ai_global_password_enabled" name="deepseek_ai_global_password_enabled" value="1" <?php checked(1, $global_pw_enabled, true); ?> /> 启用全局密码</label>
                                        <br><br>
                                        <input type="password" id="deepseek_ai_global_password_new" value="" placeholder="留空不修改" autocomplete="new-password" style="width:200px;" <?php disabled(!$global_pw_enabled); ?>/>
                                        <button type="button" class="button" id="save-global-password" style="margin-left:10px;" <?php disabled(!$global_pw_enabled); ?>>确定</button>
                                        <span id="global-password-status" style="margin-left:10px;color:green;display:none;">已保存</span>
                                        <p class="description">设置全站文章访问密码。如单篇文章未设置密码，则使用此密码。关闭后全局密码不生效。</p>
                                    </td>
                                </tr>
                                <tr valign="top">
                                    <th scope="row">密码提示</th>
                                    <td>
                                        <input type="text" name="deepseek_ai_password_hint" value="<?php echo esc_attr(get_option('deepseek_ai_password_hint', '请输入访问密码')); ?>" />
                                        <p class="description">密码输入框上方的提示文字。</p>
                                    </td>
                                </tr>
                                <tr valign="top">
                                    <th scope="row">引导内容 (HTML)</th>
                                    <td>
                                        <textarea name="deepseek_ai_password_guide_html" id="deepseek-ai-password-guide" rows="5" style="width:100%;"><?php echo esc_textarea(get_option('deepseek_ai_password_guide_html', '如需获取密码，请关注公众号。')); ?></textarea>
                                        <br>
                                        <button type="button" class="button" id="generate-guide-html" style="margin-top:8px;">AI生成</button>
                                        <span id="guide-html-status" style="margin-left:10px;color:green;display:none;">已生成</span>
                                        <p class="description">密码输入框下方的自定义引导内容，可插入二维码、链接等HTML。</p>
                                    </td>
                                </tr>
                                <tr valign="top">
                                    <th scope="row">AI生成提示词</th>
                                    <td>
                                        <input type="text" name="deepseek_ai_guide_prompt" id="deepseek-ai-guide-prompt" value="<?php echo esc_attr(get_option('deepseek_ai_guide_prompt')); ?>" style="width:100%;" />
                                        <p class="description">AI生成引导内容时的提示词。建议明确要求"务必返回带有HTML标签的片段"。</p>
                                    </td>
                                </tr>
                            </table>
                        </div>

                        <!-- 调试设置 Tab -->
                        <div id="tab-debug" class="settings-tab">
                            <h2>调试设置</h2>
                            <div class="notice notice-warning inline"><p><strong>注意：</strong>调试模式会记录详细的运行信息，可能会影响性能。建议仅在需要时启用。</p></div>
                            <table class="form-table">
                                 <tr valign="top">
                                    <th scope="row">启用调试模式</th>
                                    <td>
                                        <label><input type="checkbox" name="deepseek_ai_debug_enabled" value="1" id="debug_enabled_checkbox" <?php checked(1, get_option('deepseek_ai_debug_enabled', false), true); ?> /> 启用</label>
                                        <p class="description">启用调试模式将记录插件的详细运行信息。</p>
                                    </td>
                                </tr>
                                <tr valign="top">
                                    <th scope="row">调试级别</th>
                                    <td>
                                        <?php $debug_level = get_option('deepseek_ai_debug_level', 'info'); ?>
                                        <select name="deepseek_ai_debug_level" id="debug_level_select">
                                            <option value="debug" <?php selected($debug_level, 'debug'); ?>>调试 (Debug) - 最详细</option>
                                            <option value="info" <?php selected($debug_level, 'info'); ?>>信息 (Info) - 一般信息</option>
                                            <option value="warning" <?php selected($debug_level, 'warning'); ?>>警告 (Warning) - 仅警告和错误</option>
                                            <option value="error" <?php selected($debug_level, 'error'); ?>>错误 (Error) - 仅错误</option>
                                        </select>
                                    </td>
                                </tr>
                                <tr valign="top">
                                    <th scope="row">记录模块</th>
                                    <td>
                                        <label style="margin-right: 15px;"><input class="debug_module_checkbox" type="checkbox" name="deepseek_ai_debug_frontend" value="1" <?php checked(1, get_option('deepseek_ai_debug_frontend', false), true); ?> /> 前端</label>
                                        <label style="margin-right: 15px;"><input class="debug_module_checkbox" type="checkbox" name="deepseek_ai_debug_ajax" value="1" <?php checked(1, get_option('deepseek_ai_debug_ajax', false), true); ?> /> AJAX</label>
                                        <label><input class="debug_module_checkbox" type="checkbox" name="deepseek_ai_debug_api" value="1" <?php checked(1, get_option('deepseek_ai_debug_api', false), true); ?> /> API</label>
                                    </td>
                                </tr>
                                <tr valign="top">
                                    <th scope="row">调试日志</th>
                                    <td>
                                        <button type="button" id="view-debug-log" class="button">查看调试日志</button>
                                        <button type="button" id="clear-debug-log" class="button">清空日志</button>
                                        <button type="button" id="download-debug-log" class="button">下载日志</button>
                                        <div id="debug-log-content" style="display:none;"></div>
                                    </td>
                                </tr>
                            </table>
                        </div>

                        <!-- 插件更新 Tab -->
                        <div id="tab-update" class="settings-tab">
                            <h2>插件更新</h2>
                            <table class="form-table" role="presentation">
                                <tbody>
                                    <tr>
                                        <th scope="row">当前版本</th>
                                        <td><strong><?php echo esc_html($this->plugin->get_version()); ?></strong></td>
                                    </tr>
                                    <tr>
                                        <th scope="row">手动检查更新</th>
                                        <td>
                                            <button id="manual-update-check-btn" class="button">检查更新</button>
                                            <span class="spinner" style="float: none; vertical-align: middle;"></span>
                                            <p class="description">点击按钮，立即从更新服务器获取最新版本信息。</p>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                            <div id="update-check-result" style="margin-top: 20px; display: none;"></div>
                        </div>

                        <?php submit_button('保存设置'); ?>
                    </form>
                </div>
            </div>
        </div>
        <script type="text/javascript">
        jQuery(document).ready(function($) {
            // --- 数据 ---
            const allProvidersConfig = <?php echo json_encode($all_providers_config, JSON_UNESCAPED_UNICODE); ?>;
            const savedProviderConfigs = <?php echo json_encode($saved_provider_configs, JSON_UNESCAPED_UNICODE); ?>;
            
            // --- 元素 ---
            const $providerSelect = $('#ai_provider_select');

            // --- 函数 ---
            function updateVisibleProviderBlock(providerId) {
                $('.provider-settings-block').hide();
                $('#provider-settings-' + providerId).show();
            }

            // --- 事件处理 ---
            // Tab 切换
            $('.deepseek-ai-settings-sidebar li').on('click', function() {
                const tabId = $(this).data('tab');
                $('.deepseek-ai-settings-sidebar li').removeClass('active');
                $(this).addClass('active');
                $('.settings-tab').removeClass('active');
                $('#tab-' + tabId).addClass('active');

                // 根据当前标签页显示或隐藏"保存设置"按钮
                if (tabId === 'update') {
                    $('form .submit').hide();
                } else {
                    $('form .submit').show();
                }
            });

            // AI 提供商切换
            $providerSelect.on('change', function() {
                updateVisibleProviderBlock($(this).val());
            }).trigger('change');
            
            // 调试开关
            $('#debug_enabled_checkbox').on('change', function() {
                const isEnabled = $(this).is(':checked');
                $('#debug_level_select, .debug_module_checkbox').prop('disabled', !isEnabled);
            }).trigger('change');

            // 全局密码开关
            $('#deepseek_ai_global_password_enabled').on('change', function(){
                var enabled = $(this).is(':checked');
                $('#deepseek_ai_global_password_new, #save-global-password').prop('disabled', !enabled);
                $.post(ajaxurl, {
                    action: 'deepseek_ai_toggle_global_password',
                    enabled: enabled ? 1 : 0,
                    _ajax_nonce: '<?php echo wp_create_nonce("deepseek_ai_save_global_password"); ?>'
                });
            });

            // 保存全局密码
            $('#save-global-password').on('click', function(){
                var pwd = $('#deepseek_ai_global_password_new').val();
                if(pwd === ''){ alert('请输入新密码'); return; }
                $.post(ajaxurl, {
                    action: 'deepseek_ai_save_global_password',
                    password: pwd,
                    _ajax_nonce: '<?php echo wp_create_nonce("deepseek_ai_save_global_password"); ?>'
                }, function(resp){
                    if(resp.success){
                        $('#global-password-status').show().delay(1500).fadeOut();
                        $('#deepseek_ai_global_password_new').val('');
                } else {
                        alert('保存失败: ' + (resp.data || '未知错误'));
                    }
                });
            });

            // AI 生成引导
            $('#generate-guide-html').on('click', function(){
                var btn = $(this);
                btn.prop('disabled', true).text('生成中...');
                var prompt = $('#deepseek-ai-guide-prompt').val();
                $.post(ajaxurl, {
                    action: 'deepseek_ai_generate_guide_html',
                    prompt: prompt,
                    _ajax_nonce: '<?php echo wp_create_nonce("deepseek_ai_generate_guide_html"); ?>'
                }, function(resp){
                    btn.prop('disabled', false).text('AI生成');
                    if(resp.success && resp.data){
                        $('#deepseek-ai-password-guide').val(resp.data);
                        $('#guide-html-status').show().delay(1500).fadeOut();
                    } else {
                        alert('生成失败: ' + (resp.data || '请检查API设置'));
                    }
                });
            });
            
            // --- 调试日志 ---
            const ajaxNonce = '<?php echo wp_create_nonce("deepseek_ai_nonce"); ?>';
            $('#view-debug-log').click(function() {
                var $content = $('#debug-log-content');
                if ($content.is(':visible')) {
                    $content.hide();
                    $(this).text('查看调试日志');
                } else {
                    $(this).text('正在加载...');
                    $.post(ajaxurl, { action: 'deepseek_ai_get_debug_log', nonce: ajaxNonce })
                        .done(function(response) {
                        if (response.success) {
                                $content.text(response.data || '日志为空.').show();
                            $('#view-debug-log').text('隐藏日志');
                        } else {
                            alert('获取日志失败: ' + response.data);
                            $('#view-debug-log').text('查看调试日志');
                        }
                        })
                        .fail(function() {
                        alert('请求失败');
                        $('#view-debug-log').text('查看调试日志');
                    });
                }
            });
            
            $('#clear-debug-log').click(function() {
                if (confirm('确定要清空调试日志吗？此操作不可恢复。')) {
                    $.post(ajaxurl, { action: 'deepseek_ai_clear_debug_log', nonce: ajaxNonce })
                        .done(function(response) {
                        if (response.success) {
                            $('#debug-log-content').text('').hide();
                            $('#view-debug-log').text('查看调试日志');
                            alert('日志已清空');
                        } else {
                            alert('清空失败: ' + response.data);
                        }
                    });
                }
            });
            
            $('#download-debug-log').click(function() {
                window.open(`${ajaxurl}?action=deepseek_ai_download_debug_log&nonce=${ajaxNonce}`, '_blank');
            });

            // --- 插件更新 ---
            $('#manual-update-check-btn').on('click', function() {
                const $btn = $(this);
                const $spinner = $btn.siblings('.spinner');
                const $resultDiv = $('#update-check-result');

                $btn.prop('disabled', true);
                $spinner.addClass('is-active');
                $resultDiv.hide().html('').removeClass('notice notice-success notice-warning notice-error');

                $.post(ajaxurl, {
                    action: 'deepseek_ai_manual_update_check',
                    _ajax_nonce: '<?php echo wp_create_nonce("deepseek_ai_manual_update_check"); ?>',
                }).done(function(response) {
                    if (response.success) {
                        const data = response.data;
                        let html = '';
                        let noticeClass = 'notice-info';

                        if (data.status === 'update_available') {
                            noticeClass = 'notice-warning';
                            html += `<p><strong>发现新版本: ${data.new_version}</strong></p>`;
                            html += '<div><strong>更新日志:</strong><br>' + data.changelog + '</div>';
                            html += `<p><button class="button button-primary deepseek-do-update-btn" style="margin-top:10px;">立即更新到 ${data.new_version}</button></p>`;
                            html += '<div class="update-progress" style="display:none; margin-top: 10px;"></div>';
                        } else if (data.status === 'no_update') {
                            noticeClass = 'notice-success';
                            html = `<p>${data.message}</p>`;
                        } else { // error
                            noticeClass = 'notice-error';
                            html = `<p>${data.message}</p>`;
                        }
                        $resultDiv.addClass('notice ' + noticeClass).css('border-left-width', '4px').html(html).show();
                    } else {
                        $resultDiv.addClass('notice notice-error').css('border-left-width', '4px').html(`<p>检查失败: ${(response.data && response.data.message) || '未知错误'}</p>`).show();
                    }
                }).fail(function() {
                    $resultDiv.addClass('notice notice-error').css('border-left-width', '4px').html('<p>请求失败，请检查浏览器控制台或服务器错误日志。</p>').show();
                }).always(function() {
                    $btn.prop('disabled', false);
                    $spinner.removeClass('is-active');
                });
            });

            // AJAX 执行更新
            $('#update-check-result').on('click', '.deepseek-do-update-btn', function(e) {
                e.preventDefault();
                const $btn = $(this);
                const $resultDiv = $('#update-check-result');
                const $progressDiv = $resultDiv.find('.update-progress');

                if (!confirm('确定要开始更新插件吗？在更新过程中，网站可能会短暂进入维护模式。')) {
                    return;
                }

                $btn.prop('disabled', true).text('正在更新，请勿离开此页面...');
                $progressDiv.html('<span class="spinner is-active" style="float:none; vertical-align:middle;"></span>&nbsp;正在下载和安装更新...').show();

                $.post(ajaxurl, {
                    action: 'deepseek_ai_do_plugin_update',
                    _ajax_nonce: '<?php echo wp_create_nonce("deepseek_ai_do_plugin_update"); ?>'
                }).done(function(response) {
                    if (response.success) {
                        $resultDiv.removeClass('notice-warning').addClass('notice-success').html('<p>✅ 更新完成！请刷新页面以体验最新版插件。</p>');
                    } else {
                        $btn.prop('disabled', false).text('更新失败，请重试');
                        $progressDiv.html('<p style="color:red;"><strong>错误:</strong> ' + response.data.message + '</p>');
                    }
                }).fail(function() {
                    $btn.prop('disabled', false).text('更新失败，请重试');
                    $progressDiv.html('<p style="color:red;">请求发送失败，请检查网络连接或服务器错误日志。</p>');
                });
            });
        });
        </script>
        <?php
    }
    
    // AJAX相关
    public function ajax_save_global_password() {
        check_ajax_referer('deepseek_ai_save_global_password');
        if (!current_user_can('manage_options')) {
            wp_send_json_error('无权限');
        }
        $pwd = isset($_POST['password']) ? sanitize_text_field($_POST['password']) : '';
        if ($pwd === '') {
            wp_send_json_error('密码不能为空');
        }
        update_option('deepseek_ai_global_password_hash', password_hash($pwd, PASSWORD_DEFAULT));
        wp_send_json_success();
    }
    
    public function ajax_generate_guide_html() {
        check_ajax_referer('deepseek_ai_generate_guide_html');
        if (!current_user_can('manage_options')) {
            wp_send_json_error('无权限');
        }
        $api = $this->plugin->get_api();
        // 生成引导内容时优先用前端传递的prompt，无则用默认值
        $default_prompt = '请生成一段适合放在密码输入框下方的HTML引导内容，要求如下：只返回HTML标签片段，不要出现任何代码块标记（如```、```html、```代码等）；不要使用<style>标签；所有样式请用内联style属性写在标签上；内容可包含关注公众号、二维码、联系方式等，字数80字内；只返回HTML标签本身，不要有多余的换行、缩进或解释说明，不要有其它任何内容。';
        $prompt = isset($_POST['prompt']) && $_POST['prompt'] ? sanitize_text_field($_POST['prompt']) : $default_prompt;
        $result = $api->generate_guide_content($prompt);
        if ($result && is_string($result)) {
            // 只返回内容，不自动保存，需用户点击"保存设置"按钮才保存
            wp_send_json_success($result);
        } else {
            wp_send_json_error('AI生成失败');
        }
    }
    
    public function ajax_toggle_global_password() {
        check_ajax_referer('deepseek_ai_save_global_password');
        if (!current_user_can('manage_options')) {
            wp_send_json_error('无权限');
        }
        $enabled = isset($_POST['enabled']) && $_POST['enabled'] ? 1 : 0;
        update_option('deepseek_ai_global_password_enabled', $enabled);
        wp_send_json_success();
    }

    public function ajax_manual_update_check() {
        check_ajax_referer('deepseek_ai_manual_update_check');

        if (!current_user_can('update_plugins')) {
            wp_send_json_error(array('message' => '您没有更新插件的权限。'), 403);
        }

        $updater = $this->plugin->get_updater();
        if (!$updater) {
            wp_send_json_error(array('message' => '更新器未初始化。'), 500);
        }

        $result = $updater->force_check_update();

        if (isset($result['status']) && $result['status'] === 'error') {
            wp_send_json_error($result, 500);
        }

        wp_send_json_success($result);
    }

    public function ajax_do_plugin_update() {
        check_ajax_referer('deepseek_ai_do_plugin_update');

        if (!current_user_can('update_plugins')) {
            wp_send_json_error(['message' => '您没有更新插件的权限。'], 403);
        }

        // 加载WordPress更新相关文件
        include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
        
        // 刷新插件更新缓存
        wp_cache_flush();
        delete_site_transient('update_plugins');

        // 使用静默的皮肤，避免产生不必要的HTML输出
        $skin = new \WP_Ajax_Upgrader_Skin();
        $upgrader = new \Plugin_Upgrader($skin);
        $result = $upgrader->upgrade(plugin_basename(DEEPSEEK_AI_PLUGIN_FILE));

        if (is_wp_error($result)) {
            wp_send_json_error(['message' => $result->get_error_message()], 500);
        } elseif ($result === false) {
            // 当$result为false时，错误信息通常存储在$skin->errors中
            $error_message = '更新失败，但未提供具体错误信息。';
            if (isset($skin->errors) && !empty($skin->errors)) {
                $errors = [];
                foreach ($skin->errors as $error_array) {
                    $errors = array_merge($errors, $error_array);
                }
                if (!empty($errors)) {
                    $error_message = implode(' ', $errors);
                }
            }
            wp_send_json_error(['message' => $error_message], 500);
        }
        
        // $result 为 true 表示成功
        wp_send_json_success(['message' => '插件更新成功。']);
    }
} // class DeepSeekAI_Admin

} // end if (!class_exists('DeepSeekAI_Admin'))